package struts.acion;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import struts.form.ActionForm;
import struts.form.FullForm;
import struts.util.XmlBean;

public class ActionServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//得到请求路径
		String requestUrl = getPath(request.getServletPath());
		//得到struts-config.xml信息
		Map<String, XmlBean> map=  (Map<String, XmlBean>) this.getServletContext().getAttribute("struts");
		XmlBean bean = map.get(requestUrl);
		ActionForm form = null;
		Action action = null;
		String url = "";
		try {
			//将表单内容封装到对象
			form = FullForm.getForm(bean.getBeanClass(), request);
			//得到请求的Action
			Class actionClass = Class.forName(bean.getActionType());
			action = (Action) actionClass.newInstance();
			//执行action方法，得到转发的url
			url = action.excute(request, form, bean.getForward());
		} catch (Exception e) {
			e.printStackTrace();
		}
		//获得转发器对象
		RequestDispatcher rd = request.getRequestDispatcher(url);
		//转发请求
		rd.forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

	private static String getPath(String url){
		return url.split("\\.")[0];
	}
}
